
package com.elong.android.specialhouse.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.adapter.common.BaseViewHolder;
import com.elong.android.specialhouse.adapter.common.PowerAdapter;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.HouseInfoRequestParam;
import com.elong.android.specialhouse.entity.HouseItemList;
import com.elong.android.specialhouse.entity.response.GetMemberInfoResp;
import com.elong.android.specialhouse.request.GetAuthStateReq;
import com.elong.android.specialhouse.request.GetLandlordHouseListReq;
import com.elong.android.specialhouse.request.GetMemberInfoListReq;
import com.elong.android.specialhouse.ui.observeablescrollview.ObservableListView;
import com.elong.android.specialhouse.ui.observeablescrollview.ObservableScrollViewCallbacks;
import com.elong.android.specialhouse.ui.observeablescrollview.ScrollState;
import com.elong.android.specialhouse.utils.DateTimeUtils;
import com.elong.android.specialhouse.utils.ImageLoaderUtils;
import com.elong.android.specialhouse.utils.ToastUtils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;
import com.elong.myelong.utils.Utils;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Random;


public class HomePageOthersActivity extends BaseVolleyActivity<IResponse<?>> implements ObservableScrollViewCallbacks, AdapterView.OnItemClickListener {
    private static final String TAG = HomePageOthersActivity.class.getSimpleName();

    private static final String ID_STATUS_EXAMINE_NOSUBMIT_DESC = "身份未审核";
    private static final String ID_STATUS_EXAMINING_DESC = "身份审核中";
    private static final String ID_STATUS_EXAMINE_NOT_OK_DESC = "身份审核未通过";
    private static final String ID_STATUS_EXAMINE_NONE_DESC = "身份证未验证";
    private static final String ID_STATUS_EXAMINE_OK = "身份证已验证";
    private static final int PAGE_SIZE = 100;

    /**
     * sex indicator
     * 2 : female
     * 1 : male
     */
    private static final int FEMALE = 2;
    private static final int MALE = 1;

    private GetMemberInfoResp mGetMemberInfoResp = null;

    private ObservableListView lvOtherHouse;
    private ImageView ivBackTop;
    private RelativeLayout lytCommonHead;
    private LinearLayout llOtherHouseHeader;
    /**
     * User Name
     */
    private ImageView ivPhoto;
    private TextView tvName;
    private TextView tvSex;
    private TextView tvBirthday;
    private TextView tvAuthState;
    private TextView tvContacts;
    private TextView tvDefaultSynopsis;
    private TextView tvSynopsis;
    private Long mLandlordId;
    private String mLandlordName;

    /**
     * 证件类型审核状态
     */
    private String mIdentityPass;
    /**
     * 证件类型审核状态描述
     */
    private String mIdentityPassDesc;
    private PowerAdapter<HouseItemList> mAdapter;
    private ArrayList<HouseItemList> mDataList;
    private int mCurrentPageIndex = 0;
    private int mTotalNumber;

    private int mScreenHeight;
    private int mScreenWidth;

    private boolean isScrollToBottom;

    private int defaultValue;

    @Override
    protected void initContentView() {
        setContentView(R.layout.act_home_page_others);
        setHeader(R.string.home_page);

        lvOtherHouse = (ObservableListView) findViewById(R.id.lv_other_house);
        ivBackTop = (ImageView) findViewById(R.id.iv_back_top);
        lytCommonHead = (RelativeLayout) findViewById(R.id.lyt_common_head);

        llOtherHouseHeader = (LinearLayout) View.inflate(this, R.layout.item_home_page_others_head, null);
        ivPhoto = (ImageView) llOtherHouseHeader.findViewById(R.id.iv_photo);
        tvName = (TextView) llOtherHouseHeader.findViewById(R.id.tv_name);
        tvSex = (TextView) llOtherHouseHeader.findViewById(R.id.tv_sex);
        tvBirthday = (TextView) llOtherHouseHeader.findViewById(R.id.tv_birthday);
        tvAuthState = (TextView) llOtherHouseHeader.findViewById(R.id.tv_auth_state);
        tvContacts = (TextView) llOtherHouseHeader.findViewById(R.id.tv_contact_he);
        tvDefaultSynopsis = (TextView) llOtherHouseHeader.findViewById(R.id.tv_default_synopsis);
        tvSynopsis = (TextView) llOtherHouseHeader.findViewById(R.id.tv_synopsis);

        setListener();
    }

    private void setListener() {
        tvContacts.setOnClickListener(this);
        ivBackTop.setOnClickListener(this);

        lvOtherHouse.setOnItemClickListener(this);
        lvOtherHouse.addScrollViewCallbacks(this);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    private void initData() {
        mScreenHeight = Utils.getScreenHeight(this);
        mScreenWidth = Utils.getScreenWidth(this);
        mLandlordId = Long.valueOf(getIntent().getStringExtra(AppConstants.LANDLORD_ID));
        mLandlordName = getIntent().getStringExtra(AppConstants.LANDLORD_NAME);

        defaultValue = new Random().nextInt(2);
        requestAuthState();
        requestBaseInfo();
    }

    /**
     * 获取房东身份验证状态
     */
    private void requestAuthState() {
        GetAuthStateReq req = new GetAuthStateReq();
        req.Uid = mLandlordId;
        requestHttp(req, ApartmentAPI.getAuthState, StringResponse.class);
    }

    /**
     * ask for account info from server
     */
    private void requestBaseInfo() {
        GetMemberInfoListReq req = new GetMemberInfoListReq();
        req.UidList = new ArrayList<Long>();
        if (mLandlordId != 0) {
            req.UidList.add(mLandlordId);
        }
        req.TagType = "0";
        requestHttp(req, ApartmentAPI.getMemberInfoList, true);
    }

    private void requestHouseList() {
        GetLandlordHouseListReq req = new GetLandlordHouseListReq();
        req.LandlordId = mLandlordId;
        req.PageIndex = mCurrentPageIndex;
        req.PageSize = PAGE_SIZE;
        requestHttp(req, ApartmentAPI.getLandlordHousesList, false);
    }

    @Override
    public void
    onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        ApartmentAPI action = (ApartmentAPI) request.getRequestOption().getHusky();
        JSONObject result = null;
        try {
            result = JSON.parseObject(((StringResponse) t).getContent());
        } catch (Exception e) {
            ToastUtils.show(this, R.string.parse_error);
            return;
        }
        if (handleIsError(request, result)) {
            return;
        }
        switch (action) {
            case getMemberInfoList:
                onGetMemberInfoSuccess(result);
                requestHouseList();
                break;
            case getLandlordHousesList:
                onGetLandlordHousesListSuccess(result);
                break;
            case getAuthState:
                saveAuthState(result);
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_contact_he:
                gotoChatPage();
                break;
            case R.id.iv_back_top:
                toListTop();
            default:
                break;
        }
    }

    private void onGetMemberInfoSuccess(JSONObject result) {
        JSONObject memberInfo = result.getJSONObject("MemberInfoList");
        if (memberInfo == null) return;
        JSONObject jo = memberInfo.getJSONObject(mLandlordId + "");
        mGetMemberInfoResp = JSON.parseObject(jo.toJSONString(), GetMemberInfoResp.class);
        inflateBaseInfo();
        lvOtherHouse.addHeaderView(llOtherHouseHeader);
        lvOtherHouse.setAdapter(getPowerAdapter());
        lvOtherHouse.setDividerHeight(0);
    }

    private void onGetLandlordHousesListSuccess(JSONObject result) {
        mTotalNumber = result.getIntValue("HouseCount");
        JSONArray array = result.getJSONArray("HouseItemList");
        if (array == null) {
            return;
        }

        mDataList = (ArrayList<HouseItemList>) JSON.parseArray(array.toJSONString(), HouseItemList.class);
        if (mDataList == null || mDataList.size() < 1) {
            return;
        }

        showHisHouse();
        if (mAdapter == null) {
            mAdapter = getPowerAdapter();
            lvOtherHouse.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        hideTitleView();
    }

    private void hideHisHouse() {
        llOtherHouseHeader.findViewById(R.id.rl_his_house).setVisibility(View.GONE);
    }

    private void showHisHouse() {
        llOtherHouseHeader.findViewById(R.id.rl_his_house).setVisibility(View.VISIBLE);
        ((TextView)llOtherHouseHeader.findViewById(R.id.tv_label_his_house)).getPaint().setFakeBoldText(true);
    }

    @NonNull
    private PowerAdapter<HouseItemList> getPowerAdapter() {
        return new PowerAdapter<HouseItemList>(this, R.layout.item_home_page_house_list, mDataList) {
            @Override
            protected void convert(BaseViewHolder holder, HouseItemList item) {
                holder.setImageUrl(R.id.iv_apartment_image, item.RoomPicUrl);
                holder.setText(R.id.tv_desc, item.HouseName);
                holder.setText(R.id.tv_city, item.CityName);
                holder.setText(R.id.tv_address, TextUtils.isEmpty(item.BusinessAreaName) ? item.DistrictName : item.BusinessAreaName);
            }
        };
    }

    private void inflateBaseInfo() {
        if (mGetMemberInfoResp == null) return;
        setPhoto();
        setName();
        setSex();
        setBirthday();
        setAuthState();
        setSynopsis();
        hideHisHouse();
    }

    private void setName() {
        if (TextUtils.isEmpty(mGetMemberInfoResp.NickName)) {
            tvName.setVisibility(View.GONE);
        } else {
            tvName.setText(mGetMemberInfoResp.NickName);
            tvName.getPaint().setFakeBoldText(true);
        }
    }

    private void setSex() {
        tvSex.setText(mGetMemberInfoResp.Sex == MALE ? "男" : "女");
    }

    private void setBirthday() {
        if (TextUtils.isEmpty(mGetMemberInfoResp.Birth)) {
            tvBirthday.setText(R.string.birthday_default);
            return;
        }
        tvBirthday.setText(DateTimeUtils.changeDateFormat(mGetMemberInfoResp.Birth, "yyyy_MM_dd", "yyyy年MM月dd日")
        );
    }

    private void setPhoto() {
        setPhotoHeight(mScreenWidth);
        if (!TextUtils.isEmpty(mGetMemberInfoResp.Avatar)) {
            ImageLoader.getInstance().displayImage(mGetMemberInfoResp.Avatar, ivPhoto, ImageLoaderUtils.getHeaderImageOptions());
        } else {
            //男
            if (mGetMemberInfoResp.Sex == 1) {
                ivPhoto.setImageResource(defaultValue == 1 ? R.drawable.use_photo_male1 : R.drawable.use_photo_male2);
            }
            //女
            else {
                ivPhoto.setImageResource(defaultValue == 1 ? R.drawable.use_photo_female1 : R.drawable.use_photo_female2);

            }
        }
    }

    private void setPhotoHeight(int height) {
        ViewGroup.LayoutParams params = ivPhoto.getLayoutParams();
        params.width = Utils.getScreenWidth(this);
        params.height = height;
        ivPhoto.setLayoutParams(params);
    }

    private void setSynopsis() {
        ((TextView)llOtherHouseHeader.findViewById(R.id.tv_label_his_profile)).getPaint().setFakeBoldText(true);

        if (TextUtils.isEmpty(mGetMemberInfoResp.Intro)) {
            tvDefaultSynopsis.setVisibility(View.VISIBLE);
            tvSynopsis.setVisibility(View.GONE);
        } else {
            tvDefaultSynopsis.setVisibility(View.GONE);
            tvSynopsis.setVisibility(View.VISIBLE);
            tvSynopsis.setText("    "+mGetMemberInfoResp.Intro);
        }
    }

    private void setAuthState() {
        tvAuthState.setText("Y".equals(mIdentityPass) ? ID_STATUS_EXAMINE_OK : ID_STATUS_EXAMINE_NONE_DESC);
    }

    private void toListTop() {
        lvOtherHouse.setSelection(0);
        lvOtherHouse.smoothScrollToPosition(0, 0);
        ivBackTop.setVisibility(View.GONE);
        showTitleView();
    }

    private void gotoChatPage() {
        if (!Account.getInstance().isLogin()){
            startActivity(LoginActivity.class,null);
            return;
        }
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_ID, mLandlordId);
        intent.putExtra(AppConstants.ACTIVITY_KEY_FRIEND_NAME, mLandlordName);
        startActivity(intent);
    }

    /**
     * 保存身份验证状态
     */
    private void saveAuthState(JSONObject result) {
        mIdentityPass = result.getString(AppConstants.USER_IDENTITYPASS);
        mIdentityPassDesc = result.getString(AppConstants.USER_IDENTITYPASSDECRIPTION);
        setAuthState();
        if (TextUtils.isEmpty(tvAuthState.getText().toString())) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position > 0) {
            gotoDetailPage(position);
        }
    }

    private void gotoDetailPage(int position) {
        Intent intent = new Intent(this, ApartmentDetailsActivity.class);
        HouseInfoRequestParam param = new HouseInfoRequestParam();
        param.HouseItemList = mAdapter.getItem(position - 1);
        intent.putExtra("ApartmentInfoRequestParam", param);
        startActivity(intent);
    }


    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        ivBackTop.setVisibility(Math.abs(scrollY) > mScreenHeight ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
        if (scrollState == ScrollState.UP) {
            hideTitleView();
        } else if (scrollState == ScrollState.DOWN) {
            showTitleView();
        }
    }

    private void showTitleView() {
        ViewPropertyAnimator.animate(lytCommonHead).setDuration(500).alpha(0.5f).start();
        ViewPropertyAnimator.animate(lytCommonHead).setDuration(500).translationY(0).start();
    }

    private void hideTitleView() {
        ViewPropertyAnimator.animate(lytCommonHead).setDuration(500).alpha(0).start();
        ViewPropertyAnimator.animate(lytCommonHead).setDuration(500).translationY(-lytCommonHead.getHeight()).start();
    }
}
